const api = require('../../../api/mop_api');
import { toast, log, err, back } from '../../../utils/wxapi';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    typelist: [],
    catId: '',
    costPrice: '',
    price: '',
    salePrice: '',
    title: '',
    remark: '',
    coverUrl: [],
    // 声明变量接用户点击修改菜品时跳转过来的参数
    id: '',
    page: 1,
    size: 30,
    item: {},
    mchId: '',
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    if (options.id) {
      const id = options.id;
      this.setData({ id });
      try {
        const { respCode, source, msg } = await api.goodGet({ id });
        if (respCode === 200) {
          let { title, catId, costPrice, price, salePrice, remark, coverUrl, id } = JSON.parse(source);
          coverUrl = JSON.parse(coverUrl);
          this.setData({
            title,
            catId,
            costPrice,
            price,
            salePrice,
            remark,
            coverUrl,
            id,
          });
        } else {
          toast(msg);
        }
      } catch (error) {
        err(error);
        throw error;
      }
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.type();
    this.setData({ mchId: wx.getStorageSync('mchId') });
  },
  // 点击修改
  async postPut() {
    let { title, catId, costPrice, price, salePrice, remark, coverUrl, id, mchId } = this.data;
    coverUrl = JSON.stringify(coverUrl);
    const data = {
      title,
      catId,
      costPrice,
      price,
      salePrice,
      remark,
      coverUrl,
      mchId,
      id,
    };
    if (title === '') {
      toast('请输入菜品名称');
    } else if (catId === '') {
      toast('请选择菜品类型');
    } else if (costPrice === '') {
      toast('请输入菜品成本');
    } else if (price === '') {
      toast('请输入菜品价格');
    } else if (salePrice === '') {
      toast('请输入菜品销售价格');
    } else {
      try {
        const res = await api.goodPut(data);
        if (res.respCode === 200) {
          back();
          toast('修改成功');
        } else {
          toast(res.msg);
        }
      } catch (error) {
        err(error);
        throw error;
      }
    }
  },
  async type() {
    const { page, size } = this.data;
    try {
      const { respCode, source, msg } = await api.typelist({ page, size });
      if (respCode === 200) {
        const typelist = JSON.parse(source);
        log(typelist);
        this.setData({ typelist });
        wx.hideLoading();
      } else {
        toast(msg);
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  seltype(e) {
    this.setData({ catId: e.currentTarget.dataset.id });
  },
  upload() {
    wx.showLoading({
      title: '上传中',
    });
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: res => {
        const head = res.tempFiles[0].tempFilePath;
        this.compress_img(head);
      },
      fail: () => {
        toast('上传失败');
        wx.hideLoading();
      },
    });
  },
  compress_img(img_src) {
    let timestamp = new Date().valueOf();
    const query = wx.createSelectorQuery();
    query
      .select('#myCanvas')
      .fields({
        node: true,
        size: true,
      })
      .exec(res => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        let img = canvas.createImage();
        img.src = img_src;
        img.onload = () => {
          let stylewidth = img.width;
          let styleheight = img.height;
          var sizelimit = 200;
          if (Math.max(stylewidth, styleheight) > sizelimit) {
            var percent = sizelimit / Math.max(stylewidth, styleheight);
            stylewidth = Math.trunc(stylewidth * percent);
            styleheight = Math.trunc(styleheight * percent);
          }
          canvas.width = stylewidth;
          canvas.height = styleheight;
          this.setData({
            cHeight: styleheight,
            cWidth: stylewidth,
          });
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
          wx.canvasToTempFilePath({
            canvas: canvas,
            fileType: 'jpg',
            quality: 1,
            success: res => {
              wx.cloud.uploadFile({
                cloudPath: 'good_img/' + timestamp + '.jpg',
                filePath: res.tempFilePath,
                success: res => {
                  toast('上传成功');
                  let { coverUrl } = this.data;
                  coverUrl.unshift(res.fileID);
                  this.setData({ coverUrl });
                },
                fail: () => {
                  toast('上传失败');
                },
              });
            },
          });
        };
      });
  },
  async postgood() {
    let { title, catId, costPrice, price, salePrice, remark, coverUrl, mchId } = this.data;
    coverUrl = JSON.stringify(coverUrl);
    const data = {
      title,
      catId,
      costPrice,
      price,
      salePrice,
      remark,
      coverUrl,
      mchId,
    };
    if (title === '') {
      toast('请输入菜品名称');
    } else if (catId === '') {
      toast('请选择菜品类型');
    } else if (costPrice === '') {
      toast('请输入菜品成本');
    } else if (price === '') {
      toast('请输入菜品价格');
    } else if (salePrice === '') {
      toast('请输入菜品销售价格');
    } else {
      try {
        const res = await api.goodpost(data);
        if (res.respCode === 200) {
          toast('添加成功');
          back();
        } else {
          toast(res.msg);
        }
      } catch (error) {
        err(error);
        throw error;
      }
    }
  },
  delimg(e) {
    const i = e.currentTarget.dataset.index;
    let { coverUrl } = this.data;
    coverUrl.splice(i, 1);
    this.setData({ coverUrl });
  },
});
